/* Copyright 2009 Sony Mathew, Minneapolis MN. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
package com.xsm.gwt.widgets.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;

/**
 * Loads content from an HTTP URL using a GET command.
 * 
 * @author Sony Mathew
 */
public class HttpSource implements Source {

    private final String url;
    private List<Consumer> consumers = new ArrayList<Consumer>();

    /**
     * Retreive content from the given url.
     * 
     * @param url: a url that can br normalized using
     *      {@link GWTUtil#normalizeURL(String)}
     * 
     * author Sony Mathew
     */
    public HttpSource(String url) {
        this.url = GWTUtil.normalizeURL(url);
    }
    /**
     * Consumers are notified of content retrieved or failures.  
     * @see com.xsm.gwt.widgets.client.Source#addConsumer(com.xsm.gwt.widgets.client.Source.Consumer)
     */
    public void addConsumer(Consumer c) {
        consumers.add(c);
    }

    /**
     * @see com.xsm.gwt.widgets.client.Source#refresh()
     */
    public void refresh() {        
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
        
        try {
            Request request = builder.sendRequest(null, new RequestCallback() {
                public void onResponseReceived(Request request,
                        Response response) {
                    if (200 == response.getStatusCode()) {
                        setContent(response.getText());
                    } else {
                        Throwable t = new RuntimeException("Unable to load " +
                                "content from URL, HTTP Status [" + 
                                    response.getStatusCode() + "," + 
                                    response.getStatusText() + "]");
                        failedContentLoad(t);                        
                    }
                }
                
                public void onError(Request request, Throwable e) {
                    failedContentLoad(e);
                }                
            });
        } catch (RequestException e) {
            failedContentLoad(e);
        }        
    }
    
    private void setContent(String content) {
        for(Consumer c : consumers) {
            c.setContent(this, content);
        }
    }
    
    private void failedContentLoad(Throwable e) {
        for(Consumer c : consumers) {
            c.failedContentLoad(this, e);
        }        
    }
    
    @Override
    public String toString() {
        return "HttpSource[" + url + "]";
    }
    
    
}
